package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperdStatement;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void  parse(InputStream inputStream) throws Exception{
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        paseSelect(rootElement, namespace);
        paseUpdate(rootElement, namespace);
        paseDelete(rootElement, namespace);
    }

    public void paseSelect(Element rootElement, String namespace){
        List<Element> list = rootElement.selectNodes("//select");
        list.stream().forEach(e->{
            String id = e.attributeValue("id");
            String resultType = e.attributeValue("resultType");
            String paramterType = e.attributeValue("paramterType");
            String sqlText = e.getTextTrim();
            MapperdStatement mapperdStatement = new MapperdStatement(id, resultType, paramterType, sqlText);
            configuration.getMapperdStatementMap().put(namespace + "." + id, mapperdStatement);
        });
    }

    public void paseUpdate(Element rootElement, String namespace){
        List<Element> list = rootElement.selectNodes("//update");
        list.stream().forEach(e->{
            String id = e.attributeValue("id");
            String resultType = "java.lang.Integer";
            String paramterType = e.attributeValue("paramterType");
            String sqlText = e.getTextTrim();
            MapperdStatement mapperdStatement = new MapperdStatement(id, resultType, paramterType, sqlText);
            configuration.getMapperdStatementMap().put(namespace + "." + id, mapperdStatement);
        });
    }
    public void paseDelete(Element rootElement, String namespace){
        List<Element> list = rootElement.selectNodes("//delete");
        list.stream().forEach(e->{
            String id = e.attributeValue("id");
            String resultType = "java.lang.Integer";
            String paramterType = e.attributeValue("paramterType");
            String sqlText = e.getTextTrim();
            MapperdStatement mapperdStatement = new MapperdStatement(id, resultType, paramterType, sqlText);
            configuration.getMapperdStatementMap().put(namespace + "." + id, mapperdStatement);
        });
    }

}
